/**
 * Created by pengling on 2015/5/25.
 */

var Minisearch = function(){
};
Minisearch.prototype = {
    url : "./js/pt_data.json",
    tpl : "<li><a href='javascript:;' title='_platname_'>_platnametxt_</a></li>",
    listid : 'minisearch-list',
    init : function(option){
        var that = this;
        if(option.hasOwnProperty('id')){
            this.inputid = option.id;
        }else{
            console.log("bad id");
        }
        if(option.hasOwnProperty('url')){
            this.url = option.url;
        }
        this._getdata();
        $("#"+ this.listid + "").on("click", "a", function(){
            $("#"+that.inputid).val($(this).attr('title'));
            $("#"+ that.listid).empty();
            $("#"+ that.listid).hide();
        })
    },

    _getdata : function(){
        var that = this;
        $.ajax({
            url : this.url,
            type : "GET",
            dataType : "json",
            success : function(data){
                if(data.length){
                    that._data = data;
                    that._bind(that.inputid,that._data);
                }
            }
        })
    },

    _bind : function(id,data){
        var that = this;
        $("#"+id).keyup(function(e){
            $("#"+ that.listid).empty();
            $("#"+ that.listid).hide();
            if(e.keyCode != 13){
                var val = $.trim( $("#"+id).val())
                console.log(id,val)
                if(val.length==0){
                    return;
                }
                var match_res = $.grep(data,function(item){
                    if(item.platName.indexOf(val)>=0 || item.platPin.indexOf(val)>=0 || item.allPlatPin.indexOf(val)>=0){
                        return true;
                    }else{
                        return false;
                    }
                })

                $.each(match_res,function(i,item){
                    var name_txt = item.platName.replace(val,"<i>"+val+"</i>");
                    var fix = that.tpl.replace('_platname_',item.platName).replace('_platnametxt_',name_txt);
                    $("#"+ that.listid).append(fix);
                })
                if($("#"+ that.listid).children().length){
                    $("#"+ that.listid).show();
                }

            }else{
                $("#"+id).closest('form').submit();
            }
        })
    }
}


